import socket
import requests
import urllib3
import ping3

urllib3.disable_warnings()
ping3.EXCEPTIONS = True


class ICMP:
    """ping"""

    def __init__(self, host=None, timeout=4):
        self.host = host
        self.timeout = timeout

    def heartbeat(self):
        ping3.ping(self.host, timeout=self.timeout)


class TCP(ICMP):
    """端口探测"""
    def __init__(self, host, port, timeout=60):
        self.port = port
        super().__init__(host=host, timeout=timeout)

    def heartbeat(self):
        with socket.create_connection((self.host, self.port), self.timeout) as sock:
            sock.shutdown(socket.SHUT_RDWR)


class Http:
    """http服务存活"""
    def __init__(self, url, method='GET', timeout=90, desire_code=200, **kwargs):
        self.url = url
        self.method = method
        self.timeout = timeout
        self.desire_code = desire_code
        self.kwargs = kwargs

    def heartbeat(self):
        kwargs = {'timeout': self.timeout, 'verify': False, **self.kwargs}
        resp = requests.request(self.method, self.url, **kwargs)
        if resp.status_code != self.desire_code:
            raise Exception('the status_code is not desired')


class ThirdLib:
    """第三方库 心跳校验由第三方自行校验
    数据库/kafka/promethues/xxx
    """
    def __init__(self, third_lib):
        self.third_lib = third_lib

    def heartbeat(self):
        self.third_lib.heartbeat()


if __name__ == '__main__':
    ICMP('192.168.101.79').heartbeat()
    TCP('192.168.101.79', 80).heartbeat()
    Http('https://192.168.101.79/', desire_code=200).heartbeat()
